package multithreadedgui.gui;

import multithreadedgui.model.DemoModel;
import multithreadedgui.model.PropertyChangeListener;
import multithreadedgui.util.GBC;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Use at own risk.
 * Creation data:
 * User: Alex
 * Date: 12/04/12
 * Time: 19:53
 */
public class DemoFrame extends JFrame implements PropertyChangeListener {

    private JPanel      contentPanel;
    private JLabel      piLabel;
    private JButton     piButton;
    private JButton     exerciseButton;

    private int counter;

    private DemoModel model;

    public DemoFrame() {
        model = new DemoModel();
        model.addPropertyChangeListener(this);
        createComponents();
        addComponents();
        addListeners();
    }

    private void createComponents() {
        contentPanel    = new JPanel();
        piLabel         = new JLabel();
        piButton        = new JButton("Push me and watch magic happen!");
        exerciseButton  = new JButton("You have clicked me " + counter + " times");
        exerciseButton.setEnabled(false);
    }

    private void addComponents() {
        this.setLayout(new GridBagLayout());
        this.add(contentPanel, new GBC(0,0).setFill(GBC.BOTH).setWeight(1,1));

        contentPanel.setLayout(new BorderLayout());
        contentPanel.add(piButton,          BorderLayout.LINE_START);
        contentPanel.add(piLabel,           BorderLayout.CENTER);
        contentPanel.add(exerciseButton,    BorderLayout.PAGE_END);
    }

    private void addListeners() {
        piButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                piButton.setEnabled(false);
                exerciseButton.setEnabled(true);
                piLabel.setText("Calculating ... wait for it ... ");
                model.calculatePi();
            }
        });

        exerciseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                exerciseButton.setText("You have clicked me " + ++counter + " times");
            }
        });
    }

    @Override
    public void notifyPropertyChanged(String propertyName) {
        if("pi".equals(propertyName)) {
            piLabel.setText(String.valueOf(model.getPi()));
            piButton.setEnabled(true);
            exerciseButton.setEnabled(false);
            piButton.setText("Wanna try again?");
        }
    }
}
